using System.Data;
using GEM.Application.Contracts.AI;
using GEM.Application.Contracts.Jwt;
using GEM.Application.Contracts.Storage;
using GEM.Domain.Events;
using GEM.Domain.Repositories;
using GEM.Infrastructure.AI;
using GEM.Infrastructure.AI.Services;
using GEM.Infrastructure.DB;
using GEM.Infrastructure.Events;
using GEM.Infrastructure.Extensions;
using GEM.Infrastructure.Jwt;
using GEM.Infrastructure.Redis;
using GEM.Infrastructure.Repositories;
using GEM.Infrastructure.Storage;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Npgsql;

namespace GEM.Infrastructure;

public static class ServiceCollectionExtenstion
{
    // 扩展方法，方便在 Program.cs 里一行代码注册所有基础设施服务
    public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
    {
        //获取PostgreSql连接字符串
        var connString = configuration.GetConnectionString("pgsql");

        //注册 AppDbContext，配置使用 PostgreSQL 数据库
        services.AddDbContext<AppDbContext>(options =>
        {
            options.UseNpgsql(connString);
        });


        // Dapper注册，配置使用 PostgreSQL 数据库
        services.AddScoped<IDbConnection>(optioons =>
            new NpgsqlConnection(connString)
        );

        // 注册Dapper通用仓储接口和实现
        services.AddScoped(typeof(IDapperRepository<>), typeof(DapperRepository<>));

        // 注册Ef通用仓储接口和实现I
        services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));

        //获取redis连接字符串
        var redisConnStr = configuration.GetConnectionString("redis");
        if (string.IsNullOrWhiteSpace(redisConnStr))
        {
            throw new InvalidOperationException("Redis 连接字符串未配置!!!");
        }

        // 注册 AddSingleton,配追使用Redis 数据库
        services.AddSingleton<IRedisService>(new RedisService(redisConnStr));

        services.AddSingleton<IJwtTokenService, JwtTokenService>();


        // 添加MediatR
        services.AddMediatR(cfg =>
        {
            cfg.RegisterServicesFromAssembly(typeof(ServiceCollectionExtenstion).Assembly);
        });

        // 注册领域事件调度器
        services.AddScoped<IDomainEventDispatcher, MediatRDomainEventDispatcher>();

        // 注册Deepseek服务
        services.Configure<DeepseekSettings>(configuration.GetSection("Deepseek"));
        services.AddHttpClient<IAIService, DeepseekService>();

        // 注册文件仓储
        services.AddScoped<GEM.Domain.Repositories.IFileRepository, GEM.Infrastructure.Repositories.FileRepository>();
        // 注册本地存储实现，路径可根据实际情况配置
        services.AddSingleton<GEM.Application.Contracts.Storage.IStorageProvider>(new GEM.Infrastructure.Storage.LocalStorageProvider("Uploads"));

        // 添加跨域配置
        services.AddGemCors(configuration);

        // 返回服务集合，支持链式调用
        return services;
    }

}
